$(document).ready(function(){
    /***  商户列表  ***/
    var timeFlag = true
    var priceFlag = true
    var type = 1
    var like = ''
    $('.sortItemAre').on('click',function(){
        var sortType = $(this).data('type')
        // console.log(timeFlag)
        // console.log(priceFlag)
        
        $('#timeImg').attr('src','../../img/community-service/up.png')
        $('#priceImg').attr('src','../../img/community-service/up.png')
        $('.timeTxt').css('color','black')
        $('.priceTxt').css('color','black')
        if(sortType == 'time'){
            $('.timeTxt').css('color','#0b67ff')
            if(timeFlag == true){
                timeFlag = false
                $('#timeImg').attr('src','../../img/community-service/downBlue.png')      
                type = 2          
                getGoodsList(goodsPageNo,showNum,type,like);
            }else{
                timeFlag = true
                $('#timeImg').attr('src','../../img/community-service/upBlue.png')   
                type = 1  
                getGoodsList(goodsPageNo,showNum,type,like);
            }
        }else if(sortType == 'price'){
            $('.priceTxt').css('color','#0b67ff')
            if(priceFlag == true){
                priceFlag = false
                $('#priceImg').attr('src','../../img/community-service/downBlue.png')      
                type = 4   
                getGoodsList(goodsPageNo,showNum,type,like);       
            }else{
                priceFlag = true
                $('#priceImg').attr('src','../../img/community-service/upBlue.png')   
                type = 3  
                getGoodsList(goodsPageNo,showNum,type,like);
            }
        }
    })

    $('#searchTxt').on('click',function(){
        like = $('.search-box').val()
        getGoodsList(goodsPageNo,showNum,type,like);
    })
    //获取商品列表
    var goodsPageNo = 1,showNum=10;
    var goodsList = '';
    function getGoodsList(p,showNum,type,like){
        getAjax(`${global.apiUrl}/admin_get_health_shop_product`,function(res){
            console.log(res);
            if(res.list.length == 0){
                $("#page").paging({
                    pageNo:0,
                    totalPage: 0, //总页数
                    totalSize: 0,
                    callback: function(num) {
                        getGoodsList(num,showNum,type,like)
                    }
                });
                var html = `
                        <tr>
                            <td colspan="8" align="center">暂无商品</td>
                        </tr>`
                $('#goodsList').html(html);
            }else{
                $("#page").paging({
                    pageNo:p,
                    totalPage: Math.ceil(res.count/showNum), //总页数
                    totalSize: res.count,
                    callback: function(num) {
                        getGoodsList(num,showNum,type,like)
                        goodsPageNo = num
                    }
                });
                var html = '';
                goodsList = res.list;
                var list = res.list;
                for(var i in list){
                    html += `
                        <tr>
                            <td class="shop-img">
                                <img src="${list[i].head_img}" alt="">
                            </td>
                            <td>${list[i].product_name}</td>
                            <td>${list[i].content}</td>
                            <td>${list[i].gg}</td>
                            <td>${list[i].price}</td>
                            <td>${list[i].pay_no}</td>
                            <td>${list[i].pay_yes?list[i].pay_yes:0}</td>
                            <td class="control-td themeColor">
                                <span class="reset" data-toggle="modal" data-target="#GoodsModal" data-id="${list[i].id}" data-type="2">修改</span>
                                <span class="delete" data-id="${list[i].id}" style="margin-left: 15px">删除</span>
                                <span class="evaluation" data-toggle="modal" data-target="#evaluationModal" data-id="${list[i].id}" style="margin-left: 15px">查看评论</span>
                                ${getStatus(list[i].status,list[i].id)}
                            </td>
                        </tr>
                `
                }
                $('#goodsList').html(html);
            }
        },{
            p:p,
            num:showNum,
            type: type,
            like: like,
            shop_id: global.shop_id
        })
    }
    getGoodsList(goodsPageNo,showNum,type,like);
    
    function getStatus(status,id){
        var html = ''
        switch (status) {
            case '0':
                html += `<span class="select" data-id="${id}" data-type="0" style="margin-left: 15px">申请精选</span>`
                break;
            case '1':
                html += `<span class="select" data-id="${id}" data-type="1" style="margin-left: 15px">取消精选</span>`
                break;
            case '4':
                html += `<span style="margin-left: 15px">等待审核</span>`
                break;
        }
        return html
    }

    /** 添加商品 **/
    function setShopImgUrl(res){
        document.getElementById('goods-img-url').value = res;
    }
    imgUpload('goods-img-select','goods-img-show',setShopImgUrl);

    
    var imgurl;
    var imgs = [];  //商品head展示图片
    var imgArr = imgUploadShow('content-img-select','content-img-show');
    //新图删除
    $('#content-img-show').on('click','.cancle',function(){
        var index = $(this).parent().index();
        imgArr.splice(index,1);
        var contentImgList = document.getElementById('content-img-show');
        // // console.log(contentImgList);
        var contentNewImgList = contentImgList.getElementsByClassName('new')[0];
        var contentImgItem = document.getElementsByClassName('content-img-item');
        // // console.log(contentImgItem);
        contentNewImgList.removeChild(contentImgItem[index])

    })
    //旧图删除
    $('#content-img-show').on('click','.del',function(){
        var index = $(this).parent().index();
        // console.log(index);
        imgs.splice(index,1);
        // console.log(imgs)
        var contentImgList = document.getElementById('content-img-show');
        // // console.log(contentImgList);
        var contentNewImgList = contentImgList.getElementsByClassName('old')[0];
        var contentImgItem = document.getElementsByClassName('content-old-img-item');
        // // console.log(contentImgItem);
        contentNewImgList.removeChild(contentImgItem[index])
        // // console.log(imgs);
    })
    $('#upload-content-img').on('click',function(){
        allImgUpload(imgArr,setContentImgUrl)
    });
    function setContentImgUrl(res){
        // console.log(res)
        if(res.length != 0){
            imgurl = {
                banner_img : res
            } ;
            imgs.push(imgurl)
            // console.log(imgs);
            $('#upload-content-img').css('display','none');
        }
    }

    var imgurl2;
    var imgs2 = [];  //商品head展示图片
    var imgArr2 = imgUploadShow('content-img-select2','content-img-show2');
    //新图删除
    $('#content-img-show2').on('click','.cancle',function(){
        var index = $(this).parent().index();
        imgArr.splice(index,1);
        var contentImgList = document.getElementById('content-img-show2');
        // // console.log(contentImgList);
        var contentNewImgList = contentImgList.getElementsByClassName('new')[0];
        var contentImgItem = contentNewImgList.getElementsByClassName('content-img-item');
        // // console.log(contentImgItem);
        contentNewImgList.removeChild(contentImgItem[index])

    })
    //旧图删除
    $('#content-img-show2').on('click','.del',function(){
        var index = $(this).parent().index();
        // // console.log(index);
        imgs2.splice(index,1);
        var contentImgList = document.getElementById('content-img-show2');
        // // console.log(contentImgList);
        var contentNewImgList = contentImgList.getElementsByClassName('old')[0];
        var contentImgItem = contentNewImgList.getElementsByClassName('content-old-img-item2');
        // // console.log(contentImgItem);
        contentNewImgList.removeChild(contentImgItem[index])
        // // console.log(imgs);
    })
    $('#upload-content-img2').on('click',function(){
        allImgUpload(imgArr2,setContentImgUrl2)
    });
    function setContentImgUrl2(res){
        // console.log(res)
        if(res.length != 0){
            imgurl2 = {
                url:res
            } ;
            imgs2.push(imgurl2)
            // console.log(imgs2);
            $('#upload-content-img2').css('display','none');
        }
    }
    
    var goosClass = '';
    function getGoodsClass(){
        getAjax(`${global.apiUrl}/get_community_health_shop_product_class`,function(res){
            console.log(res);
            var html = '';
            var addGoodsClass = '';
            goodsClass = res;
            for(var i in res){
                addGoodsClass += `
                    <div class="checkbox">
                        <label>
                            <input type="radio" class="class-checked" name="class" value="${res[i].id}"> ${res[i].class_name}
                        </label>
                    </div>
                `
            }
            $('#add-shop-class-box').html(addGoodsClass);

        },{
            community_id: global.community_id
        })
    }
    getGoodsClass();

    $('#GoodsModal').on('show.bs.modal',function(event){
        var modal = $(this);
        var btnThis = $(event.relatedTarget);
        var type = btnThis.data('type');
        modal.find('#upType').val(type);
        // modal.find('#upload-content-img').css('display','block');
        modal.find('#goodsId').val('');
        // // console.log(type);
        var goodsName = modal.find('#goodsName');
        goodsName.val('');
        var shopPrice = modal.find('#shopPrice');
        shopPrice.val('');
        var shopNumber = modal.find('#shopNumber');
        shopNumber.val('')
        var goodsDesc = modal.find('#goodsDesc');
        goodsDesc.val('');
        var shopSpecifications = modal.find('#shopSpecifications')
        shopSpecifications.val('')
        var shopImg = modal.find('#goods-img-url');
        shopImg.val('');

        modal.find('#content-img-show .old').html('');
        modal.find('#content-img-show .new').html('');//可能存在bug
        modal.find('#content-img-show2 .old').html('');
        modal.find('#content-img-show2 .new').html('');//可能存在bug
        modal.find("#goods-img-show").html(`<div>图片预览</div>`);
        $('#upload-content-img').css('display','none');
        $('#upload-content-img2').css('display','none');
        //分类
        var obj = $(".class-checked");
        obj.attr('checked',false);

        var parameterItemAre = modal.find('.parameterItemAre')
        parameterItemAre.html('')


        //根据type判断是2修改还是1新增
        if(type == 1){
            modal.find('#GoodsModalLabel').text('添加商品');
        }else if(type == 2){
            modal.find('#GoodsModalLabel').text('修改商品信息');
            var goodsId = btnThis.data('id')
            modal.find('#goodsId').val(goodsId);
            var goodsInfo = '';
            for(var i in goodsList){
                if(goodsList[i].id == goodsId){
                    goodsInfo = goodsList[i]
                    break;
                }
            }
            // console.log(goodsInfo)
            goodsName.val(goodsInfo.product_name);
            shopPrice.val(goodsInfo.price);
            shopSpecifications.val(goodsInfo.gg);
            goodsDesc.val(goodsInfo.content);
            shopImg.val(goodsInfo.head_img);
            shopNumber.val(goodsInfo.pay_no)
            modal.find('#goods-img-show').html(`<img src="${goodsInfo.head_img}" />`);

            imgs = goodsInfo.top_img;
            var top_img = goodsInfo.top_img;
            // // console.log(head_banner);
            var html = '';
            for(var j in top_img){
                html+= `
                    <div class="content-old-img-item">
                        <img src="${top_img[j].banner_img}" alt="">
                        <div class="del themeColor">删 除</div>
                    </div>
                `
            }
            modal.find('#content-img-show .old').html(html);

            imgs2 = goodsInfo.content_img;
            var content_img = goodsInfo.content_img;
            // // console.log(head_banner);
            var html2 = '';
            for(var z in content_img){
                html2 += `
                    <div class="content-old-img-item2">
                        <img src="${content_img[z].url}" alt="">
                        <div class="del themeColor">删 除</div>
                    </div>
                `
            }
            modal.find('#content-img-show2 .old').html(html2);

            obj.each(function(){
                var that = $(this);
                if(that.val() == goodsInfo.class_id){
                    // console.log(that.val());
                    that.prop('checked',true);
                }
            })


            var html3 = ''
            for(var p in goodsInfo.canshu){
                
                html3 += `
                            <div class="parameterItem">
                                <div class="parameter-group">
                                    <label for="parameter-name">名称</label>
                                    <input type="text" name="name" class="parameter-name" value="${goodsInfo.canshu[p].name}">
                                </div>
                                <div class="parameter-group">
                                    <label for="parameter-value">内容</label>
                                    <input type="text" name="value" class="parameter-value" value="${goodsInfo.canshu[p].text}">
                                </div>
                            </div>
                `
                index ++
            }
            $('.parameterItemAre').append(html3)

        }

    })
    
    //添加参数
    var index = 0
    $('#parameterBtn').on('click',function(){
        index ++ 
        var html = `
                    <div class="parameterItem">
                        <div class="parameter-group">
                            <label for="parameter-name">名称</label>
                            <input type="text" name="name" class="parameter-name">
                        </div>
                        <div class="parameter-group">
                            <label for="parameter-value">内容</label>
                            <input type="text" name="value" class="parameter-value">
                        </div>
                    </div>
        `
        
        $('.parameterItemAre').append(html)
        if(index > 0){
            $('#parameterDelBtn').css('display','block')
        }
    })

    //删除
    $('#parameterDelBtn').on('click',function(){
        index --
        $('.parameterItemAre').children('.parameterItem').eq(index).remove()
        if(index == 0){
            $('#parameterDelBtn').css('display','none')
        }
    })

    /** 添加 修改 **/
    $('#addGoods').on('click',function(){
        var shopType = $("#upType").val();
        // console.log('type:',type);
        if(index == 0){
            alert('请填写参数')
        }
        var nameList = []
        var parameterNameList = $('.parameterItemAre .parameter-name')
        parameterNameList.each(function(){
            var that = $(this);
            nameList.push(that.val())
        })
        var valueList = []
        var parameterValueList = $('.parameterItemAre .parameter-value')
        parameterValueList.each(function(){
            var that = $(this);
            valueList.push(that.val())
        })
        var parameterList = []
        for(var i=0;i < index;i++){
            var data = {
                name: nameList[i],
                text: valueList[i]
            }
            parameterList.push(data)
            
        }
        //获取选择的类别
        var obj = document.getElementsByClassName("class-checked");
        var check_class = '';
        for(k in obj){
            if(obj[k].checked)
                check_class=obj[k].value;
        }
        if(check_class)
        // // console.log(check_class)
        
        //获取商品名称
        var goodsName = $('#goodsName').val();
        //获取商品价格
        var shopPrice = $('#shopPrice').val(); 
        var shopNumber = $('#shopNumber').val()
        //获取商品规格
        var shopSpecifications = $('#shopSpecifications').val();
        //获取简介
        var goodsDesc = $('#goodsDesc').val();
        //获取缩略图
        var shopImg = $('#goods-img-url').val();
        
        
        //数据
        if(goodsName == ''||shopPrice == ''||goodsDesc == '' || shopImg=='' || check_class == '' ||shopNumber == '' || shopSpecifications == ''){
            alert('请将信息填写完整！')
        }else{
            if(imgs.length == 0){
                alert('请上传商品展示图片！')
                return
            }
            if(imgs2.length == 0){
                alert('请上传商品详情图片！')
                return
            }
            var data = {}
            if(shopType == 1){
                data = {
                    "shop_id": global.shop_id,
                    "product_name": goodsName,
                    "price":shopPrice,
                    "pay_no": shopNumber,
                    "head_img":shopImg,
                    "content_img": imgs2,
                    "top_img": imgs,
                    "status": 0,
                    "class_id": check_class,
                    "content": goodsDesc,
                    'yunfei': 0,
                    "city": sessionStorage.getItem('city'),
                    "gg": shopSpecifications,
                    "canshu": parameterList,
                    "community_id": global.community_id    
                }
            }else if(shopType ==2){
                //修改
                var id = $("#goodsId").val();
                data = {
                    "id": id,
                    "shop_id": global.shop_id,//shopId
                    "product_name": goodsName,
                    "price":shopPrice,
                    "pay_no": shopNumber,
                    "head_img":shopImg,
                    "content_img": imgs2,
                    "top_img": imgs,
                    "status": 0,
                    "class_id": check_class,
                    "content": goodsDesc,
                    'yunfei': 0,
                    "city": sessionStorage.getItem('city'),
                    "gg": shopSpecifications,
                    "canshu": parameterList,
                    "community_id": global.community_id
                }
            }
            
            data = JSON.stringify(data);
            console.log(data)
            var text = ''
            if(shopType == 2){
                text = '商品信息，修改成功！';
            }else if(shopType == 1){
                text = '新的商品，添加成功！';
            }
            console.log(shopType)
            postAjax(`${global.apiUrl}/admin_operation_community_health_shop_product`,function(res){
                console.log(res)
                if(res == 1){
                    alert(text);
                    $('#GoodsModal').modal('hide');
                    getGoodsList(goodsPageNo,showNum,type,like);         
                }
            },{
                type:shopType,
                pro: data
            })
        }
    })
    /** 删除 **/
    $('#goodsList').on('click','.delete',function(){
        var goodsId = $(this).data('id');
        var f = confirm('是否删除该商品');
        if(f){
            getAjax(`${global.apiUrl}/admin_operation_community_health_shop_product`,function(res){
                console.log(res);
                if(res == 1){
                    alert('商品删除成功！');
                    getGoodsList(goodsPageNo,showNum,type,like);
                }
            },{
                type:3,
                id:goodsId
            })
        }
    })

    //申请、取消精选
    $('#goodsList').on('click','.select',function(){
        var goodsId = $(this).data('id');
        var statusType = $(this).data('type');
        var text = ''
        var status = ''
        switch (statusType) {
            case 0:
                text = '申请设为精选'
                status = '4'       
                break;
            case 1:
                text = '取消设为精选'
                status = '0'
                break;
        }
        console.log(status)
        postAjax(`${global.apiUrl}/Api/Communityhealth/save_health_product_one`,function(res){
            console.log(res)
            if(res == 1){
              alert(text + '成功')
              getGoodsList(goodsPageNo,showNum,type,like);
            }
        },{id: goodsId,status: status})
    })

    var evaluationGoodsId = ''
    //评论
    $('#evaluationModal').on('show.bs.modal',function(event){
        var modal = $(this);
        var btnThis = $(event.relatedTarget);
        evaluationGoodsId = btnThis.data('id');
        var switchBtn = modal.find('.switchBtn');
        switchBtn.css('border','1px solid #b4b4b4')
        switchBtn.children('.round').css('background','#b4b4b4')
        switchBtn.eq(0).css('border','1px solid #0b67ff')
        switchBtn.eq(0).children('.round').css('background','#0b67ff')
        getEvaluationList(evaluationPageNo,showNum2,evaluationGoodsId)
    })

    var t = 0
    $(".switchBtn").on('click',function(){
        var type = $(this).data('type')
        t = type
        $('.switchBtn').css('border','1px solid #b4b4b4')
        $('.switchBtn').children('.round').css('background','#b4b4b4')
        $(this).css('border','1px solid #0b67ff')
        $(this).children('.round').css('background','#0b67ff')
        getEvaluationList(evaluationPageNo,showNum2,evaluationGoodsId)
    })

    $(".dateSearch").on('click',function(){
        getEvaluationList(evaluationPageNo,showNum2,evaluationGoodsId)
    })

    var evaluationPageNo = 1,showNum2=5;
    var evaluationList = '';
    function getEvaluationList(p,showNum2,id){
        let time = '00:00:00'
        let endTime = '23:59:59'
        var start = $('#start').val() != ''? $('#start').val() + ' ' + time: '2019-01-01' + ' ' + time;//开始时间
        var end = $('#end').val() != ''? $('#end').val() + ' ' + endTime: laydate.now(0, 'YYYY-MM-DD') + ' ' + endTime;//结束时间
        start = Date.parse(start) / 1000
        end = Date.parse(end) / 1000
        getAjax(`${global.apiUrl}/Api/Admincommunityhealthshop/get_community_health_shop_tell`,function(res){
            console.log(res);
            if(res.list.length == 0){
                $("#page2").paging({
                    pageNo:0,
                    totalPage: 0, //总页数
                    totalSize: 0,
                    callback: function(num) {
                        getEvaluationList(num,showNum2,id)
                    }
                });
                var html = `
                        <div>
                            暂无评论
                        </div>`
                $('#evaluateMainAre').html(html);
            }else{
                $("#page2").paging({
                    pageNo:p,
                    totalPage: Math.ceil(res.count/showNum2), //总页数
                    totalSize: res.count,
                    callback: function(num) {
                        getEvaluationList(num,showNum2,id)
                        evaluationPageNo = num
                    }
                });
                var html = '';
                evaluationList = res.list;
                var list = res.list;
                for(var i in list){
                    html += `
                            <div class="evaluateAre">
                                <div class="evaluateItemAre">
                                    <div class="evaluateItemTitle">
                                        <div class="userAre">
                                            <img src="${list[i].user_head_img}" style="width: 35px;height: 35px;margin-right: 15px;border-radius:  50%"/>
                                            <div style="color: black;font-size: 16px;margin-right: 15px;">${list[i].user_name}</div>
                                            <div>客户评论</div>
                                        </div>
                                        <div>${list[i].date}</div>
                                    </div>
                                    <div class="commentContent">${list[i].content}</div>
                                    <div class="evaluateImgAre">
                                        ${getEvaluateImg(list[i].content_img)}
                                    </div>
                                    ${getReplay(list[i].hf,list[i].id)}
                                    
                                </div>
                            </div>
                `
                }
                $('#evaluateMainAre').html(html);
            }
        },{
            p:p,
            num:showNum2,
            product_id: id,
            status: t,
            start_time: start,
            end_time: end,
            shop_id: global.shop_id
        })

        
    }

    function getEvaluateImg(list){
        var img = ''
        if(list.length != 0){
            var img = ''
            for(var i in list){
                img += `<img src="${global.apiUrl +  list[i]}"></img> `
            }
            
        }
        return img
    }

    function getReplay(list,id){
        console.log(list)
        var html = ''
        if(list != null){
            html += `
                    <div class="replyAre">
                        <div class="triangle"></div>
                        <div>商家回复：</div>
                        <div style="margin-top: 10px">${list.content}</div>
                    </div>    
                    `
        }else{
            html += `<div>
                        <div class="hf1" style="display: block">
                            <div class="replyAre2">
                                <div class="replyBtn" data-id="${id}">
                                    <img src="../../img/message.png">
                                    <div>回复</div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="hf2" style="display: none">
                            <div class="replyItemAre" >
                                <textarea class="replyInput" maxlength="-1" placeholder="请输入对此评论的回复" placeholder-style="" auto-focus auto-height fixed adjust-position show-confirm-bar bindconfirm="replyOk"></textarea>
                                <div class="replyItemTxtAre" >
                                    <div style="margin-right:15px;" class="cancel">取消</div>
                                    <div class="confirm" data-id="${id}">确认</div>
                                </div>
                            </div>
                        </div>
                        
                       
                    </div>`
        }
        return html
    }
    
    $('#evaluateMainAre').on('click','.replyBtn',function(){
        var id = $(this).data('id');
        $(this).parent().parent().css('display','none')
        $(this).parent().parent().next().css('display','block')
    })
    
    $('#evaluateMainAre').on('click','.cancel',function(){
        var index = $(this).data('index');
        $(this).parent().prev().val('')
        console.log($(this).parent().parent().parent().prev())
        $(this).parent().parent().parent().prev().css('display','block')
        $(this).parent().parent().parent().css('display','none')
    })
    
    $('#evaluateMainAre').on('click','.confirm',function(){
        var id = $(this).data('id');
        var index = $(this).data('index');
        var content = $(this).parent().prev().val()
        getAjax(`${global.apiUrl}/Api/Admincommunityhealthshop/tell`,function(res){
            console.log(res)
            if(res == 1){
              //成功 
              alert('回复成功')
              getEvaluationList(evaluationPageNo,showNum2,evaluationGoodsId)
            }else{
              alert('回复失败，请重试')
            }
          },{fid: id,content: content})
    })
});
